"""
Comparison the measured results of PAAm to bulky rheometry results
Created by Yuechuan Lin 
2022-03-10
Cornell University
"""
from numpy.core.arrayprint import _void_scalar_repr
from numpy.lib.recfunctions import _drop_fields_dispatcher
import matplotlib.mlab as mlab
import pandas as pd 
import os
from PyOCT import misc 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib 
from matplotlib import cm 
import matplotlib.ticker as tck
import matplotlib.ticker 
import h5py 
import time
from scipy import ndimage
from scipy.io import loadmat
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
                               AutoMinorLocator)
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.collections import PathCollection
from sklearn.neighbors import KernelDensity
# set font of plot 
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['Helvetica']
font = {'weight': 'normal',
        'size'   : 8}
matplotlib.rc('font', **font)
matplotlib.rc('text', usetex=False)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['mathtext.default'] = 'regular'


# plot 3D scatter comparison between PAAM and C3 with normalized Gre 
def RemoveNan(PosData,AmechData,FradData,GData):
    AmechData = np.squeeze(AmechData)
    FradData = np.squeeze(FradData)
    GData = np.squeeze(GData) 
    AmechDatatmp = np.zeros([])
    FradDatatmp = np.zeros([])
    GDatatmp = np.zeros([])
    PosDatatmp = np.zeros([])
    T = 0 
    for i in range(np.size(GData)):
        if ~np.isnan(GData[i]):
            if T == 0:
                AmechDatatmp = AmechData[i]
                FradDatatmp = FradData[i]
                GDatatmp = GData[i]
                PosDatatmp = np.reshape(PosData[i,:],(1,3))
                T = T + 1
            else: 
                AmechDatatmp = np.append(AmechDatatmp,AmechData[i])
                FradDatatmp = np.append(FradDatatmp,FradData[i])
                GDatatmp = np.append(GDatatmp,GData[i])
                PosDatatmp = np.append(PosDatatmp,np.reshape(PosData[i,:],(1,3)),axis=0)
                T = T + 1
    return PosDatatmp,AmechDatatmp,FradDatatmp,GDatatmp



if __name__ == "__main__":
    colors = misc.colorV()
    fid_PAAM = loadmat("./Fig1_data/ViolinPlot.mat")
    Gre_PAAM = fid_PAAM["ViolinPlot"]["Gre"][0,0]
    Gim_PAAM = fid_PAAM["ViolinPlot"]["Gim"][0,0]
    Name_PAAM = fid_PAAM["ViolinPlot"]["snames"][0,0]
    Gre_P1 = Gre_PAAM[Name_PAAM == "P1"]
    Gim_P1 = Gim_PAAM[Name_PAAM == "P1"]
    Gre_P2 = Gre_PAAM[Name_PAAM == "P2"]
    Gim_P2 = Gim_PAAM[Name_PAAM == "P2"] 

    #measurement results of bulky parallel-plate rheometer
    Rhe_Gre_P1 = np.asarray([20.4419,157.051,155.976,188.529])
    Rhe_Gim_P1 = np.asarray([12.928,33.4676,35.0087,15.5873])
    Rhe_Gre_P2 = np.asarray([73.1996,231.556,214.397,278.065])
    Rhe_Gim_P2 = np.asarray([14.0287,25.3854,30.7402,27.7394])

    #conduct Welch's t-test 
    from scipy import stats
    t1, p1 = stats.ttest_ind(Gre_P1,Rhe_Gre_P1,equal_var=False) 
    print("P1 Gre t-test p value is : {}".format(p1)) 

    t2, p2 = stats.ttest_ind(Gim_P1,Rhe_Gim_P1,equal_var=False) 
    print("P1 Gim t-test p value is : {}".format(p2)) 

    t3, p3 = stats.ttest_ind(Gre_P2,Rhe_Gre_P2,equal_var=False) 
    print("P2 Gre t-test p value is : {}".format(p3)) 

    t4, p4 = stats.ttest_ind(Gre_P2,Rhe_Gre_P2,equal_var=False) 
    print("P2 Gim t-test p value is : {}".format(p2)) 

    save_path = "" #define your save path here 
    if not os.path.isdir(save_path):
        os.mkdir(save_path) 
    
    fig1,ax1 = misc.create_fig(figsize=[2.5,2],bottom=0.2,left=0.2,right=0.95,top=0.95)
    ax1.set_ylabel(r"$G^{\prime}/G^{\prime\prime}$ (Pa)")
    ax1.set_ylim([0,450])
    flierprops = dict(marker='o', markerfacecolor='w', markersize=1,linestyle='none', markeredgecolor='k')
    boxprops_Gre_OCE = dict(color=colors[1])#,edgecolor=colors[1]) 
    boxprops_Gim_OCE = dict(color="w")#,edgecolor=colors[1]) 
    boxprops_Gre_Rhe = dict(color=colors[0])#,edgecolor=colors[0]) 
    boxprops_Gim_Rhe = dict(color="w")#,edgecolor=colors[0]) 

    red_dict_Gre_OCE =  {'patch_artist': True,'boxprops': dict(color=colors[1], facecolor=colors[1]),'capprops': dict(color=colors[1]),'flierprops': flierprops,'medianprops': dict(color="gray",alpha=0.7,lw=1),'whiskerprops': dict(color=colors[1])}
    red_dict_Gim_OCE =  {'patch_artist': True,'boxprops': dict(color=colors[1], facecolor="white"),'capprops': dict(color=colors[1]),'flierprops': flierprops,'medianprops': dict(color="gray",alpha=0.7,lw=1),'whiskerprops': dict(color=colors[1])}
    red_dict_Gre_Rhe =  {'patch_artist': True,'boxprops': dict(color=colors[0], facecolor=colors[0]),'capprops': dict(color=colors[0]),'flierprops': flierprops,'medianprops': dict(color="gray",alpha=0.7,lw=1),'whiskerprops': dict(color=colors[0])}
    red_dict_Gim_Rhe =  {'patch_artist': True,'boxprops': dict(color=colors[0], facecolor="white"),'capprops': dict(color=colors[0]),'flierprops': flierprops,'medianprops': dict(color="gray",alpha=0.7,lw=1),'whiskerprops': dict(color=colors[0])}


    widths = 0.35
    ax1.boxplot(Gre_P1,positions=[1],widths=widths,**red_dict_Gre_OCE)
    ax1.boxplot(Rhe_Gre_P1,positions=[1.5],widths=widths,**red_dict_Gre_Rhe)

    ax1.boxplot(Gim_P1,positions=[2.5],widths=widths,**red_dict_Gim_OCE)
    ax1.boxplot(Rhe_Gim_P1,positions=[3],widths=widths,**red_dict_Gim_Rhe)

    ax1.boxplot(Gre_P2,positions=[4],widths=widths,**red_dict_Gre_OCE)
    ax1.boxplot(Rhe_Gre_P2,positions=[4.5],widths=widths,**red_dict_Gre_Rhe)

    ax1.boxplot(Gim_P2,positions=[5.5],widths=widths,**red_dict_Gim_OCE)
    ax1.boxplot(Rhe_Gim_P2,positions=[6],widths=widths,**red_dict_Gre_Rhe)

    ax1.set_xticklabels([r"$G^{\prime}_{OCE}$",r"$G^{\prime}_{Rhe}$",r"$G^{\prime\prime}_{OCE}$",r"$G^{\prime\prime}_{Rhe}$",r"$G^{\prime}_{OCE}$",r"$G^{\prime}_{Rhe}$",r"$G^{\prime\prime}_{OCE}$",r"$G^{\prime\prime}_{Rhe}$"],fontsize=8,rotation=90)
    ax1.tick_params(axis='both', which='major', pad=1)

    fig1.savefig(os.path.join(save_path,"fig1_OCERheCompare.pdf"),dpi=fig1.dpi*2,transparent=True) 
    plt.show()



